package com.android.lovely.util

import android.content.Context
import com.tencent.mmkv.MMKV

/**
 *
 * @author why
 * @date 2025/3/6 15:50
 */
class MMKVUtils private constructor() {
    lateinit var mmKv: MMKV

    companion object {
//        const val DATE_FORMAT = "yyyy-MM-dd HH.mm.ss"
        val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { MMKVUtils() }
    }

    fun init(context: Context) {
        //第一种使用mmkv默认目录
        MMKV.initialize(context)
    }

    fun create(id: String): MMKVUtils{
        // 检查 mmKv 是否已经初始化
        if (::mmKv.isInitialized) {
            println("MMKV is already initialized with ID: ${mmKv.mmapID()}")
            return this
        }
        // 获取 MMKV 实例并处理可能的 null 返回值
        val newMMKV = MMKV.mmkvWithID(id, MMKV.MULTI_PROCESS_MODE)
        if (newMMKV == null) {
            println("Failed to initialize MMKV with ID: $id")
            return this
        }
        mmKv = newMMKV
        return this
    }

    fun encode(key: String, value: Any) {
        when (value) {
            is String -> mmKv.encode(key, value)
            is Int -> mmKv.encode(key, value)
            is Boolean -> mmKv.encode(key, value)
            is Long -> mmKv.encode(key, value)
            is Float -> mmKv.encode(key, value)
            is Double -> mmKv.encode(key, value)
        }
        notifyChange(key)
    }


    inline fun <reified T> decode(key: String, defaultValue: T): T = when (T::class) {
        String::class -> mmKv.decodeString(key, defaultValue as String?) as T
        Int::class -> mmKv.decodeInt(key, defaultValue as Int) as T
        Boolean::class -> mmKv.decodeBool(key, defaultValue as Boolean) as T
        Long::class -> mmKv.decodeLong(key, defaultValue as Long) as T
        Float::class -> mmKv.decodeFloat(key, defaultValue as Float) as T
        Double::class -> mmKv.decodeDouble(key, defaultValue as Double) as T
        else -> throw IllegalArgumentException("Unsupported type")
    }
}

// 定义一个接口来处理监听
fun interface MMKVChangeListener {
    fun onMMKVChanged(key: String)
}

// 维护一个监听器列表
private val mmkvChangeListeners = mutableListOf<MMKVChangeListener>()

// 注册监听的方法
fun MMKVUtils.registerChangeListener(listener: MMKVChangeListener) {
    mmkvChangeListeners.add(listener)
}

// 取消监听的方法
fun MMKVUtils.unregisterChangeListener(listener: MMKVChangeListener) {
    mmkvChangeListeners.remove(listener)
}

// 模拟 MMKV 数据变化时通知监听器
fun MMKVUtils.notifyChange(key: String) {
    mmkvChangeListeners.forEach { it.onMMKVChanged(key) }
}
